package com.haiheng.module_main.mode

import android.os.Build
import androidx.annotation.RequiresApi
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.viewModelScope
import com.haiheng.common.api.API
import com.haiheng.common.constant.AppConstant
import com.haiheng.library.log.LogUtils
import com.haiheng.library.log.LogWriter
import com.haiheng.library_base.db.KVDatabase
import com.haiheng.library_base.http.Domain
import com.haiheng.library_base.http.HttpRequest
import com.haiheng.library_base.http.api
import com.haiheng.library_base.http.post
import com.haiheng.library_base.http.postJson
import com.haiheng.library_base.model.BaseViewModel
import com.haiheng.library_base.model.SingleLiveEvent
import com.haiheng.library_base.toast.ToastUtils
import com.haiheng.library_base.utils.SPUtils
import com.haiheng.module_main.bean.req.PageQueryReq
import com.haiheng.module_main.bean.req.Wherejson
import com.haiheng.module_main.bean.res.LayerMapRes
import com.haiheng.module_main.bean.res.LoginResp
import com.haiheng.module_main.bean.res.bookcar.BookCarLoginTokenRes
import kotlinx.coroutines.launch
import java.util.Base64

/**
 *
 * @Des:
 * @Author: hwz
 * @Date:2022/4/25 0025
 * @Version: 1.0
 */
class LoginViewModel : BaseViewModel() {


    val userInfoBean = SingleLiveEvent<LoginResp>()
    val isFinishSyn = SingleLiveEvent<Boolean>()
    val isLoginFinish = SingleLiveEvent<Boolean>()

    fun login(account: String, passwor: String) {
        viewModelScope.launch {
            try {
                val request = HttpRequest(API.BOOK_CAR_PATH.GET_TOLEN)
                    .putHeader(Domain.KEY_NAME,Domain.VALUE_DEFUlT)
                    .putParam("client_id","tulink")
                    .putParam("client_secret","Tulink")
                    .putParam("grant_type","password")
                    .putParam("username",account)
                    .putParam("password",passwor)
                    .putParam("scope","edc.machine ldc.collection ldc.passport")
                var response  = post<BookCarLoginTokenRes>(request)
//                LogUtils.d("response:"+response.toJson())
                if (!response.access_token.isNullOrBlank()){
//                   var paResult =  getJwtPayload(response.access_token)
                    SPUtils.getInstance().put(AppConstant.SP_TOKEN,"${response.token_type} ${response.access_token}")
                    SPUtils.getInstance().put(AppConstant.SP_USER_LOGIN,"${account}")
//                    if (response.data.orgCode != null){
//                        SPUtils.getInstance().put(AppConstant.SP_LIBRARYCODE,response.data.orgCode)
//                    }
//                    synLayoutMap(1)
                    isLoginFinish.postValue(true)
                }else{
                    ToastUtils.showShort("登录异常，${response.errorMsg}")
                    isLoginFinish.postValue(false)
                }
                LogUtils.e("登录结果：${response.toJson()}")
//                userInfoBean.postValue(response)

            }catch (ex:Exception){
                isLoginFinish.postValue(true)
                LogWriter.e("登录异常：${ex.toString()}")
                ToastUtils.showShort("登录异常，请检查网络或者配置地址是否正确")
            }


        }

    }



    @RequiresApi(Build.VERSION_CODES.O)
    fun decodeUrlSafeBase64(input: String): ByteArray {
        // 将URL安全的Base64字符替换回标准的Base64字符
        val urlDecodedString = input.replace('-', '+').replace('_', '/')

        // 去除尾部的'='（如果有的话，但这在解码时通常不是必需的）
        // 注意：这里我们没有去除它，因为Base64.getDecoder().decode()可以自动处理

        // 使用Java的Base64类来解码
        return Base64.getDecoder().decode(urlDecodedString)
    }

    fun getJwtPayload(jwt: String): String? {
        // JWT由三部分组成，用'.'分隔
        val parts = jwt.split("\\.")
        if (parts.size != 3) {
            // 无效的JWT格式
            return null
        }

        // 第二部分是Payload
        val payload = parts[1]

        // 解码Payload
        val decodedBytes = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            decodeUrlSafeBase64(payload)
        } else {
            TODO("VERSION.SDK_INT < O")
        }

        // 将字节数组转换为字符串
        return String(decodedBytes, Charsets.UTF_8)
    }


    fun synLayoutMap(page:Int) {
        var pageQueryReq = PageQueryReq()
        pageQueryReq.page = page
        pageQueryReq.length = 100000
        var wherejson = arrayListOf<Wherejson>()
        var orgCodejson = Wherejson()
        orgCodejson.conditionalType = 0
        orgCodejson.fieldName = "OrgCode"
        orgCodejson.fieldValue = AppConstant.getLibraryCode()
        wherejson.add(orgCodejson)
        var outTypeCodejson = Wherejson()
        outTypeCodejson.conditionalType = 0
        outTypeCodejson.fieldValue = "4" ///4物理层架号 5Rfid智能书架层架号
        outTypeCodejson.fieldName = "OutType"
        wherejson.add(outTypeCodejson)
        pageQueryReq.wherejson= wherejson
        api {
            val request = HttpRequest(API.PATH.SEARCH_LAYOUT_MAP)
                .putHeader(Domain.KEY_NAME,Domain.VALUE_DEFUlT)
                .putHeader(API.PARAM.PARAM_HEADER_TOKEN,AppConstant.getToken())
                .setJsonObjec(pageQueryReq)
            var response  = postJson<LayerMapRes>(request)
            if (response.isSuccess == true){
                LogUtils.e("查询书架成功：${page}")
                if (response.data != null && response.data.size > 0){
                    KVDatabase.getDb().getLayerMap().insert(response.data)
                    synLayoutMap(page+1)
                }else{
                    isFinishSyn.postValue(true)
                    LogUtils.e("同步书架完成：${page}")
                }
            }else{
                isFinishSyn.postValue(true)
                LogUtils.w("获取书架信息失败:${response.toJson()}")
            }
        }

    }
}